package com.bestcem.xm.deliver.grpc.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.bp.xm.user.grpc.v1.services.UnsubscribeSettingServiceGrpc;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.deliver.convert.grpc.DeliverGrpcConvertMapper;
import com.bestcem.xm.deliver.grpc.client.dto.MemberDto;
import com.bestcem.xm.deliver.grpc.client.dto.MemberProjectDto;
import com.bestcem.xm.member.grpc.v1.services.*;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Component
public class MemberGrpcClient {

    @GrpcClient(GrpcClientNames.DS_MEMBER)
    private MemberServiceGrpc.MemberServiceBlockingStub stub;

    @GrpcClient(GrpcClientNames.DS_MEMBER)
    private ProjectServiceGrpc.ProjectServiceBlockingStub projectstub;

    @GrpcClient(GrpcClientNames.DS_MEMBER)
    UnsubscribeSettingServiceGrpc.UnsubscribeSettingServiceBlockingStub unsubscribeSettingServiceBlockingStub;

    private final com.bestcem.xm.deliver.convert.grpc.DeliverGrpcConvertMapper deliverGrpcConvertMapper;

    public MemberGrpcClient(DeliverGrpcConvertMapper deliverGrpcConvertMapper) {
        this.deliverGrpcConvertMapper = deliverGrpcConvertMapper;
    }

    public List<String> listMembersByFilterParam(Map<String, Object> kwargs, String condition) {
        /*return ListUtil.of("6253d80fcfd06e47cc36675c");*/
        ListMembersByFilterParamRequest.Builder builder = ListMembersByFilterParamRequest.newBuilder();
        builder.setOrgId(kwargs.get("org_id").toString());
        builder.setCondition(condition);
        builder.setUserId(kwargs.get("user_id").toString());
        builder.setSuperAdmin(Boolean.parseBoolean(kwargs.get("super_admin").toString()));
        builder.setSeniorAdmin(Boolean.parseBoolean(kwargs.get("senior_admin").toString()));
        try {
            ListMembersByFilterParamResponse response = stub.listMembersByFilterParam(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[deliver] listMembersByFilterParam, kwargs = {}, condition = {} Error; ErrorMsg: {}", JSON.toJSONString(kwargs), condition, response);
                return Collections.emptyList();
            }
            return response.getMembersList().stream().map(com.bestcem.xm.member.grpc.v1.common.Member::getId).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("[deliver] listMembersByFilterParam, kwargs = {}, condition = {} Error; ErrorMsg: {}", JSON.toJSONString(kwargs), condition, e.getMessage());
            return Collections.emptyList();
        }
    }

    public MemberDto getMemberById(String id) {
        GetMemberRequest.Builder builder = GetMemberRequest.newBuilder();
        builder.setId(id);
        try {
            GetMemberResponse response = stub.getMember(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[deliver] getMemberById {} Error; ErrorMsg: {}", id, response);
                return null;
            }
            com.bestcem.xm.member.grpc.v1.common.Member member = response.getMember();
            return deliverGrpcConvertMapper.toMemberDto(member);
        } catch (Exception e) {
            log.error("[deliver] getMemberById {} Error; ErrorMsg: {}", id, e.getMessage(), e);
            return null;
        }
    }

    public List<MemberProjectDto> listProjectsByIds(List<String> ids) {
        ListProjectsByIdsRequest.Builder builder = ListProjectsByIdsRequest.newBuilder();
        builder.addAllIds(ids);

        try {
            ListProjectsByIdsResponse response = projectstub.listProjectsByIds(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[deliver] listProjectsByIds, ids = {},  Error; ErrorMsg: {}", JSON.toJSONString(ids), response);
                return Collections.emptyList();
            }
            return response.getProjectsList().stream().map(deliverGrpcConvertMapper::toMemberProjectDto).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("[deliver] listProjectsByIds, ids = {}, Error; ErrorMsg: {}", JSON.toJSONString(ids), e.getMessage());
            return Collections.emptyList();
        }
    }

    public List<MemberDto> listMembersByIds(List<String> ids) {
        ListMembersByIdsRequest.Builder builder = ListMembersByIdsRequest.newBuilder();
        builder.addAllIds(ids);
        try {
            ListMembersByParamResponse response = stub.listMembersByIds(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[deliver] listMembersByIds, ids = {},  Error; ErrorMsg: {}", JSON.toJSONString(ids), response);
                return Collections.emptyList();
            }
            return response.getMembersList().stream().map(deliverGrpcConvertMapper::toMemberDto).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("[deliver] listMembersByIds, ids = {}, Error; ErrorMsg: {}", JSON.toJSONString(ids), e.getMessage());
            return Collections.emptyList();
        }
    }

    public boolean checkDisplayRangePermission(String orgId, String userId, String memberId) {
        CheckDisplayRangePermissionRequest.Builder builder = CheckDisplayRangePermissionRequest.newBuilder();
        builder.setOrgId(orgId);
        builder.setUserId(userId);
        builder.setMemberId(memberId);
        try {
            CheckDisplayRangePermissionResponse response = stub.checkDisplayRangePermission(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[deliver] checkDisplayRangePermission, memberId = {},  Error; ErrorMsg: {}", memberId, response);
                return false;
            }
            return response.getValid();
        } catch (Exception e) {
            log.error("[deliver] ex checkDisplayRangePermission, memberId = {}, Error; ErrorMsg: {}", memberId, e.getMessage());
            return false;
        }
    }

    public List<String> importDeliverMember(String orgId, String deliverId, String primaryKey) {
        ImportDeliverMemberRequest.Builder builder = ImportDeliverMemberRequest.newBuilder();
        builder.setOrgId(orgId);
        builder.setDeliverId(deliverId);
        builder.setPrimaryKey(primaryKey);
        try {
            ImportDeliverMemberResponse response = stub.importDeliverMember(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[deliver] importDeliverMember, deliverId = {},  Error; ErrorMsg: {}", deliverId, response);
                return Collections.emptyList();
            }
            return response.getMemberIdsList();
        } catch (Exception e) {
            log.error("[deliver] importDeliverMember, deliverId = {}, Error; ErrorMsg: {}", deliverId, e.getMessage());
            return Collections.emptyList();
        }
    }

    public List<MemberDto> ListMembersByParam(String orgId, Integer mtype, String field) {
        ListMembersByParamRequest.Builder builder = ListMembersByParamRequest.newBuilder();
        JSONObject newjson = new JSONObject();
        newjson.put("orgId", orgId);
        newjson.put("mtype", mtype);
        builder.setParam(String.valueOf(newjson));
        try {
            ListMembersByParamResponse response = stub.listMembersByParam(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[deliver] ListMembersByParam error, orgId: {} mtype: {}", orgId, mtype);
                return Collections.emptyList();
            }
            return response.getMembersList().stream().map(deliverGrpcConvertMapper::toMemberDto).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("[deliver] ListMembersByParam exp error, orgId: {} mtype: {}", orgId, mtype);
            return Collections.emptyList();
        }
    }

    /*public String genMemberSig(String member_id) {
        GenSigRequest.Builder builder = GenSigRequest.newBuilder();
        builder.setMemberId(member_id);
        try {
            GenSigResponse response = stub.genSig(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[deliver] genMemberSig, member_id = {},  Error; ErrorMsg: {}", member_id, response);
                return null;
            }
            return response.getSig();
        } catch (Exception e) {
            log.error("[deliver] listMembersByIds, member_id = {}, Error; ErrorMsg: {}", member_id, e.getMessage());
            return null;
        }
    }

    public String genOrgSig(String orgId) {
        com.bestcem.bp.xm.user.grpc.v1.services.GenSigRequest.Builder builder = com.bestcem.bp.xm.user.grpc.v1.services.GenSigRequest.newBuilder();
        builder.setOrgId(orgId);
        try {
            com.bestcem.bp.xm.user.grpc.v1.services.GenSigResponse response = unsubscribeSettingServiceBlockingStub.genSig(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[deliver] genOrgSig, orgId = {},  Error; ErrorMsg: {}", orgId, response);
                return null;
            }
            return response.getSig();
        } catch (Exception e) {
            log.error("[deliver] genOrgSig, orgId = {}, Error; ErrorMsg: {}", orgId, e.getMessage());
            return null;
        }
    }*/
}
